{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--BOOK_INFORMATION-->\n",
    "<img align=\"left\" style=\"padding-right:10px;\" src=\"figures/PHydro-cover-small.png\">\n",
    "*This is the Jupyter notebook version of the [Python in Hydrology](http://www.greenteapress.com/pythonhydro/pythonhydro.html) by Sat Kumar Tomer.*\n",
    "*Source code is available at [code.google.com](https://code.google.com/archive/p/python-in-hydrology/source).*\n",
    "\n",
    "*The book is available under the [GNU Free Documentation License](http://www.gnu.org/copyleft/fdl.html). If you have comments, corrections or suggestions, please send email to satkumartomer@gmail.com.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!--NAVIGATION-->\n",
    "< [Reading the Raster](06.05-Reading-the-Raster.ipynb) | [Contents](Index.ipynb) | [Filtering](06.07-Filtering.ipynb) >"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.6 读取矢量\n",
    "\n",
    "在本节，我们将读取在前面章节编写的矢量数据。首先，我们需要导入`ogr`库。然后我们通过指定shapefile的目录来打开数据源。之后，我们通过指定不带.shp后缀的shapefile的名称，使用`GetLayerByName`来读取shape文件。在此之后，我们打印`\\n`表示空白行。`\\n`表示一个新行，`\\t`表示缩进。现在，我们打印标题信息(SI.,Name,Latitude,Longitude)。我们使用`.format`来格式化输出。冒号(:)后的'{}'中的数字表示输出的长度。我们使用`for`循环逐个读取shapefile中的特征。从每个特征中，我们使用`GetFieldAsString`提取名称，使用`GetX`提取经度和使用`GetY`提取纬度。在最后为了避免污染数据库，我们通过指定数据源为`None`来安全地关闭它。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "SI \t Name       \t Longitude \t Latitude\n",
      "0 \t Bijnor     \t 78.100 \t \t 29.400\n",
      "0 \t Delhi      \t 77.200 \t \t 28.600\n",
      "0 \t Bangalore  \t 77.800 \t \t 13.000\n",
      "0 \t Berambadi  \t 76.600 \t \t 11.800\n"
     ]
    }
   ],
   "source": [
    "import ogr\n",
    "ds = ogr.Open( 'datas/' )\n",
    "lyr = ds.GetLayerByName('location' )\n",
    "\n",
    "print(\"\\n\")\n",
    "print(\"{} \\t {:10s} \\t {} \\t {}\".format('SI', 'Name', 'Longitude', 'Latitude'))\n",
    "for feat in lyr:\n",
    "    geom = feat.GetGeometryRef()\n",
    "    name = feat.GetFieldAsString(0)\n",
    "    lat = geom.GetX()\n",
    "    lon = geom.GetY()\n",
    "    print('{0} \\t {1:10s} \\t {2:.3f} \\t \\t {3:.3f}'.format(0, name, lat, lon ))\n",
    "\n",
    "ds = None"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
